package org.example.book.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpMethod;

import java.io.IOException;

public class HttpClientUtil {
    public static JSONObject execute(String url, HttpMethod httpMethod) {
        HttpRequestBase httpRequestBase = null;
        try {
            HttpClient httpClient = HttpClients.createDefault();
            if (httpMethod == HttpMethod.GET) {
                httpRequestBase = new HttpGet(url);
            } else {
                httpRequestBase = new HttpPost(url);
            }
            HttpEntity entity = httpClient.execute(httpRequestBase).getEntity();
            return JSONObject.parseObject(EntityUtils.toString(entity));
        } catch (ClientProtocolException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            httpRequestBase.releaseConnection();
        }
    }
}
